package com.example.demo.api;

import com.example.demo.model.User;
import com.example.demo.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest req) {
        // 去数据库查询 username是否存在 如果能找到则看一下密码是否匹配
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            // 登录失败
            System.out.println("登录失败,用户名或者密码错误" + user);
            return new User(); // 返回一个空的user对象
        }
        // 如果匹配登录成功 创建会话
        HttpSession session = req.getSession(true);//如果不存在就创建会话
        session.setAttribute("user",user);
        // 在返回之前吧password给干掉,以避免返回不必要的信息
        user.setPassword("");
        return user;
    }

    @RequestMapping("/register")
    public Object register(String username,String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int result = userMapper.insert(user);
            System.out.println("注册新增人数: " + result);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            // 如果insert抛出异常,就是名字重复,注册失败
            System.out.println("注册失败: username=" + username);
            return new User();
        }
        return user;
    }

    @RequestMapping("/userinfo")
    public Object getUserInfo(HttpServletRequest request) {
        // 先从请求中获取对话
        HttpSession session = request.getSession(false);
        if (session == null) {
            System.out.println("[getUserinfo] 当前获取不到session对象");
            return new User();
        }
        // 从会话中获取对象
        User user = (User) session.getAttribute("user");
        if (user == null) {
            System.out.println("[getUserinfo] 获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
